<?php

namespace plugin\saiadmin\app\event;

use plugin\saiadmin\app\model\system\SystemLoginLog;
use plugin\saiadmin\app\model\system\SystemOperLog;
use plugin\saiadmin\app\model\system\SystemMenu;
use support\Log;

class SystemUser
{

    private $rule = [
        '/core/user/modifyPassword' => '个人信息-安全设置-修改密码',
        '/cms/Project' => '项目管理',
    ];
    /**
     * 登录日志 
     * @param $item
     */
    public function login($item)
    {
        $ip = request()->getRealIp();
        $http_user_agent = request()->header('user-agent');
        $data['username'] = $item['username'];
        $data['ip'] = $ip;
        $data['ip_location'] = self::getIpLocation($ip);
        $data['os'] = self::getOs($http_user_agent);
        $data['browser'] = self::getBrowser($http_user_agent);
        $data['status'] = $item['status'];
        $data['message'] = $item['message'];
        $data['login_time'] = date('Y-m-d H:i:s');
        SystemLoginLog::create($data);
    }

    /**
     * 记录操作日志
     */
    public function operateLog($flag): bool
    {
        // var_export('到我这里了吗？');
        if (request()->method() === 'GET') {
            // var_export('不等于get？ 到我这里了吗？');
            return false;
        }

        $info = getCurrentInfo();
        $ip = request()->getRealIp();
        // $module = request()->plugin;
        $module = '外讲库';
        // var_export(request()->path());/cms/Message/destroy
        $rule = trim(strtolower(request()->uri()));
        // var_export('我看看到哪了？' . $rule);
        $data['username'] = $info['username'];
        $data['method'] = request()->method();
        $data['router'] = $rule;
        var_export('路由名称：' . self::getServiceName());
        Log::info('====== 路由名称 ====== ' . self::getServiceName());
        $data['service_name'] = self::getServiceName();
        $data['app'] = $module;
        $data['ip'] = $ip;
        $data['ip_location'] = self::getIpLocation($ip);
        $data['request_data'] = $this->filterParams(request()->all());
        // var_export('我看看到哪了？');
        SystemOperLog::create($data);
        return true;
    }

    protected function getServiceName(): string
    {
        // var_export('自定义 getServiceName：');
        // $path1 = request()->route->getPath();
        $path = request()->path();
        // var_export('自定义 getServiceName：path ' . $path);
        // var_export('自定义 getServiceName：path1 ' . $path1);
        // Log::info('====== 自定义 getServiceName：path ====== ' . $path);
        if (preg_match("/\{[^}]+\}/", $path)) {
            // 原始的
            // $path1 = rtrim(preg_replace("/\{[^}]+\}/", '', $path), '/');
            // var_export('====== 路由名称1111 ====== ' . $path1);
            // 修改后去掉问号后的数据
            $path = rtrim(preg_replace('/\?.*$/', '', $path), '/');
        }

        // var_export('自定义11111：' . preg_replace('/(.*)\/{1}([^\/]*)/i', '$1', $path));

        $menu = SystemMenu::where('code', $path)->findOrEmpty();
        // var_export('menu:' . $menu);
        if (!$menu->isEmpty()) {
            return $menu->getAttr('name');
        } else {
            // 正则匹配原始路由，去掉最后/后的参数
            $newPath = preg_replace('/(.*)\/{1}([^\/]*)/i', '$1', $path);
            var_export('自定义 newPath：' . preg_replace('/(.*)\/{1}([^\/]*)/i', '$1', $path));
            // 从新查询一遍
            $newMenu = SystemMenu::where('code', $newPath)->findOrEmpty();
            if (!$newMenu->isEmpty()) {
                return $newMenu->getAttr('name');
            } else {
                // var_export(123123123);
                $ruleArray = [
                    '/core/user/modifyPassword',
                ];

                // var_export('rule:' . $ruleArray);
                if (in_array($path, $ruleArray)) {
                    return $this->rule[$path];
                } else {
                    return '未知';
                }
            }
        }
    }

    /**
     * 过滤字段
     */
    protected function filterParams($params): string
    {
        $blackList = ['password', 'oldPassword', 'newPassword', 'content'];
        foreach ($params as $key => $value) {
            if (in_array($key, $blackList)) {
                $params[$key] = '******';
            }
        }
        return json_encode($params, JSON_UNESCAPED_UNICODE);
    }

    protected function getIpLocation($ip)
    {
        $ip2region = new \Ip2Region();
        try {
            $region = $ip2region->memorySearch($ip);
        } catch (\Exception $e) {
            return '未知';
        }
        list($country, $number, $province, $city, $network) = explode('|', $region['region']);
        if ($network === '内网IP') {
            return $network;
        }
        if ($country == '中国') {
            return $province . '-' . $city . ':' . $network;
        } else if ($country == '0') {
            return '未知';
        } else {
            return $country;
        }
    }

    protected function getBrowser($user_agent): string
    {
        $br = 'Unknown';
        if (preg_match('/MSIE/i', $user_agent)) {
            $br = 'MSIE';
        } elseif (preg_match('/Firefox/i', $user_agent)) {
            $br = 'Firefox';
        } elseif (preg_match('/Chrome/i', $user_agent)) {
            $br = 'Chrome';
        } elseif (preg_match('/Safari/i', $user_agent)) {
            $br = 'Safari';
        } elseif (preg_match('/Opera/i', $user_agent)) {
            $br = 'Opera';
        } else {
            $br = 'Other';
        }
        return $br;
    }

    protected function getOs($user_agent): string
    {
        $os = 'Unknown';
        if (preg_match('/win/i', $user_agent)) {
            $os = 'Windows';
        } elseif (preg_match('/mac/i', $user_agent)) {
            $os = 'Mac';
        } elseif (preg_match('/linux/i', $user_agent)) {
            $os = 'Linux';
        } else {
            $os = 'Other';
        }
        return $os;
    }
}
